//
//  XS_BuyVC.swift
//  XueDao
//
//  Created by 范东 on 2021/1/1.
//

import UIKit

class XS_BuyResponseModel: XS_BaseModel {
//    "cover": "",
//            "score": null,
//            "couponsDetailsMoney": 0,
//            "price": 1.20,
//            "currName": "名称"
    var cover = ""
    var score = "0"
    var couponsDetailsMoney = "0"
    var price = ""
    var currName = ""
    var truePrice = ""
    var couponsId = ""
}

class XS_BuyFooterView: UICollectionReusableView {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class XS_BuyVC: XS_BaseVC {
    
    var name: String?
    var remark: String?
    
    var courseClassification : String = ""
    var courseId : String = ""
    
    var couponsId : String = ""

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var priceBtn: QMUIButton!
    @IBOutlet weak var priceDetailPopView: UIView!
    
    @IBOutlet weak var originPriceLabel: UILabel!
    @IBOutlet weak var couponPriceLabel: UILabel!
    @IBOutlet weak var truePriceLabel: UILabel!
    lazy var shadowView : UIView = {
        let shadowView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: .screenWidth, height: .screenHeight))
        shadowView.backgroundColor = UIColor.qmui_color(withHexString: "#252628")?.withAlphaComponent(0.4)
        shadowView.alpha = 0
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(hidePriceDetailPopView))
        shadowView.isUserInteractionEnabled = true
        shadowView.addGestureRecognizer(tap)
        return shadowView
    }()
    
    lazy var resultPopView : XS_BuyResultPopView = {
        let resultPopView = Bundle.main.loadNibNamed("XS_BuyResultPopView", owner: nil, options: nil)?.last as! XS_BuyResultPopView
        resultPopView.delegate = self
        return resultPopView
    }()
    
    var responseModel : XS_BuyResponseModel?
    @IBOutlet weak var priceDetailPopViewHeight: NSLayoutConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "购买课程"
        priceBtn.imagePosition = .right
        priceBtn.spacingBetweenImageAndTitle = 8
        collectionView.register(UINib.init(nibName: "XS_BuyCourseItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_BuyCourseItemCell")
        collectionView.register(UINib.init(nibName: "XS_BuyCouponItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_BuyCouponItemCell")
        collectionView.register(UINib.init(nibName: "XS_BuyAccountItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_BuyAccountItemCell")
        collectionView.register(UINib.init(nibName: "XS_BuyHeaderView", bundle: Bundle.main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "XS_BuyHeaderView")
        collectionView.register(XS_BuyFooterView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "XS_BuyFooterView")
        requestData()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "icon_返回")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(buyBackBtnAction))
    }
    
    @objc func buyBackBtnAction() {
        let backActionVC = UIAlertController.init(title: "确认要放弃付款吗？", message: "未支付订单将在不久后自动关闭 请尽快支付～", preferredStyle: .alert)
        let cancelAction = UIAlertAction.init(title: "暂时放弃", style: .cancel) { (action) in
            self.navigationController?.popViewController(animated: true)
        }
        cancelAction.setValue(UIColor.lightGray, forKey: "titleTextColor")
        let sureAction = UIAlertAction.init(title: "继续支付", style: .destructive, handler: nil)
        sureAction.setValue(UIColor.orange, forKey: "titleTextColor")
        backActionVC.addAction(cancelAction)
        backActionVC.addAction(sureAction)
        
        self.present(backActionVC, animated: true, completion: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if responseModel != nil {
            let cell = collectionView.cellForItem(at: IndexPath.init(item: 0, section: 2)) as? XS_BuyAccountItemCell
            cell?.reloadData()
        }
    }
    
    func requestData(){
        XS_NetWork.requestJson("/order/queryOrderInfo",parameters: ["courseClassification":courseClassification,"courseId":courseId])
            .mapModel(type: XS_BuyResponseModel.self) // 返回 模型对象 和原始数据
            .subscribe(onNext: { model, resp in
                self.responseModel = model
                self.originPriceLabel.text = "￥"+(model?.price ?? "0")
                if (Int((model?.couponsDetailsMoney ?? "0")) ?? 0 > 0){
                    self.couponPriceLabel.text = "-"+(model?.couponsDetailsMoney ?? "0")
                }else{
                    self.couponPriceLabel.text = "无"
                }
                
                let priceNum = NSDecimalNumber(string: model?.price ?? "0")
                let couponsDetailsMoneyNum = NSDecimalNumber(string: model?.couponsDetailsMoney ?? "0")
                let value = priceNum.subtracting(couponsDetailsMoneyNum).doubleValue
                let truePrice = String.init(format: "￥%lg", value < 0 ? 0 : value)
                self.responseModel?.truePrice = truePrice
                self.truePriceLabel.text = truePrice
                self.priceBtn.setTitle(truePrice, for: .normal)
                self.collectionView.reloadData()
            }).disposed(by: disposeBag)
    }

    @IBAction func priceBtnAction(_ sender: QMUIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected{
            view.insertSubview(shadowView, belowSubview: priceDetailPopView)
            UIView.animate(withDuration: 0.25) {
                self.priceDetailPopViewHeight.constant = 152
                self.shadowView.alpha = 1
            }
            
        }else{
            UIView.animate(withDuration: 0.25) {
                self.priceDetailPopViewHeight.constant = 0
                self.shadowView.alpha = 0
            } completion: { (isFinish) in
                self.shadowView.removeFromSuperview()
            }

        }
    }
    
    @IBAction func confirmBtnAction(_ sender: UIButton) {
        //        “courseClassification”：“课程类型（线下：offline，线上：online，直播：live）”,
        //        "courseId":"课程Id",
        //        "couponsId":"优惠卷id (不传为null，则未使用优惠卷)",
        if responseModel?.currName != nil {
            resultPopView.titleLabel.text = String.init(format: "您已成功购买「%@课程」", responseModel?.currName as! CVarArg)
        }
        
        var parameters = [
            "courseClassification":courseClassification,
            "courseId":courseId,
            "couponsId":responseModel?.couponsId
        ]
        if let name = name {
            parameters["name"] = name
        }
        if let remark = remark {
            parameters["remark"] = remark
        }
        
        XS_NetWork.requestJson("/order/payMoneyByOrder",parameters: parameters)
            .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                if resp.success{
                    self.resultPopView.show(UIApplication.shared.keyWindow!, .center)
                }else{
                    self.view.makeToast(resp.msg)
                }
            }).disposed(by: disposeBag)
    }
    
    @objc func hidePriceDetailPopView(){
        self.priceBtnAction(self.priceBtn)
    }
}

extension XS_BuyVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 3
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch indexPath.section {
        case 0:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_BuyCourseItemCell", for: indexPath) as! XS_BuyCourseItemCell
            if responseModel != nil {
                cell.model = responseModel
            }
            return cell
        case 1:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_BuyCouponItemCell", for: indexPath) as! XS_BuyCouponItemCell
            if responseModel != nil {
                cell.model = responseModel
            }
            return cell
        case 2:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_BuyAccountItemCell", for: indexPath) as! XS_BuyAccountItemCell
            cell.reloadData()
            return cell
        default:
            return UICollectionViewCell.init()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        switch indexPath.section {
        case 0:
            return CGSize.init(width: .screenWidth, height: 96)
        case 1:
            return CGSize.init(width: .screenWidth - 32, height: 48)
        case 2:
            return CGSize.init(width: .screenWidth - 32, height: 48)
        default:
            return CGSize.init(width: 0, height: 0)
        }
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        switch section {
        case 1:
            return UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 16)
        case 2:
            return UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 16)
        default:
            return UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            if indexPath.section == 1 || indexPath.section == 2 {
                let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "XS_BuyHeaderView", for: indexPath) as! XS_BuyHeaderView
                headerView.titleLabel.text = indexPath.section == 1 ? "选择优惠" : "支付方式"
                return headerView
            }
            return UICollectionReusableView.init()
        }else{
            if indexPath.section == 0 {
                let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "XS_BuyFooterView", for: indexPath)
                footerView.backgroundColor = UIColor.qmui_color(withHexString: "f7f7f7")
                return footerView
            }else if indexPath.section == 2{
                let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "XS_BuyFooterView", for: indexPath)
                footerView.backgroundColor = UIColor.qmui_color(withHexString: "ffffff")
                let label = UILabel.init(frame: CGRect.init(x: 16, y: 16, width: 200, height: 16))
                label.text = "购买后可在「我的-订单」中查看"
                label.textColor = UIColor.qmui_color(withHexString: "aab1b7")
                label.font = .systemFont(ofSize: 12)
                footerView.addSubview(label)
                return footerView
            }
            return UICollectionReusableView.init()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 1 || section == 2 {
            return CGSize.init(width: .screenWidth, height: 54)
        }
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        if section == 0 {
            return CGSize.init(width: .screenWidth, height: 8)
        }else if section == 2{
            return CGSize.init(width: .screenWidth, height: 48)
        }
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch indexPath.section {
        case 1:
            //优惠券
            let couponVC = XS_CouponSubVC()
            couponVC.delegate = self
            couponVC.type = .select
            couponVC.condition = responseModel?.price ?? ""
            couponVC.coupon_id = responseModel?.couponsId ?? "";
            navigationController?.pushViewController(couponVC, animated: true)
            break
        case 2:
            //充值
            let rechargeVC = XS_RechargeVC()
            navigationController?.pushViewController(rechargeVC, animated: true)
            break
        default:
            break
        }
    }
}

extension XS_BuyVC : XS_CouponSubVCDelegate{
    func couponSubVC(couponSubVC: XS_CouponSubVC, didSelectCoupon: XS_CouponItemModel) {
        //使用条件
        let conditionRet = Int(didSelectCoupon.condition) ?? 0 > (Int(responseModel?.price ?? "0") ?? 0)
        //优惠券价格不能大于商品金额
//        let priceRet = Int(didSelectCoupon.money) ?? 0 > (Int(responseModel?.truePrice ?? "0") ?? 0)
        if (conditionRet) {
            view.makeToast("优惠券不满足条件")
            return
        }else{
            responseModel?.couponsId = didSelectCoupon.id
            responseModel?.couponsDetailsMoney = didSelectCoupon.money
            collectionView.reloadData()
            //详细数据
            couponPriceLabel.text = "-"+didSelectCoupon.money
            
            let priceNum = NSDecimalNumber(string: responseModel?.price ?? "0")
            let couponsDetailsMoneyNum = NSDecimalNumber(string: didSelectCoupon.money)
            let value = priceNum.subtracting(couponsDetailsMoneyNum).doubleValue
            let truePrice = String.init(format: "￥%lg", value < 0 ? 0 : value)
            responseModel?.truePrice = truePrice
            truePriceLabel.text = truePrice
            priceBtn.setTitle(truePrice, for: .normal)
        }
    }
}

extension XS_BuyVC : XS_BuyResultPopViewDelegate{
    func resultPopView(resultPopView: XS_BuyResultPopView, didClickOkBtn: UIButton) {
        let admissionVC = XS_AdmissionVC()
        admissionVC.responseModel = responseModel
        admissionVC.courseClassification = courseClassification
        navigationController?.pushViewController(admissionVC, animated: true)
    }
}
